<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\model\Curriculum;
use app\api\model\Department;
use app\api\model\CourseClassify;
use app\api\model\Topic;
use app\api\model\UserCurriculum;
use app\api\model\UserChapter;
use app\api\model\Chapter;
use app\admin\model\User;
use app\common\model\ScoreLog;
use app\api\model\PracticeRecord;
use app\api\model\ErrorSet;
/**
 * 课程、每日练习
 */
class Course extends Api
{


    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    /**
     * 部门列表
     */
    public function department()
    {
        $department = Department::field('id,department')->select();
        $this->success('请求成功',$department);
    }

    /**
     * 课程分类列表
     */
    public function course_classify()
    {
        $classify = CourseClassify::select();
        $this->success('请求成功',$classify);
    }

    /**
     * 每日学习
     * 课程列表
     *
     */
    public function index()
    {
        $page = $this->request->get('page');
        $limit = $this->request->get('limit');
        $cid = $this->request->get('cid');
        $did = $this->request->get('did');
        $page = empty($page) ? 1 : $page;
        $limit = empty($limit) ? 10 : $limit;
        $userId = $this->auth->id;
        if (empty($cid) && empty($did)) {
            $curriculum = Curriculum::field('img,course,quantity,support,duration,createtime')
                        ->page($page,$limit)->select();  //课程
        } else {
            if (!empty($cid)) {
                $where['cid'] = $cid;
            } elseif (!empty($did)) {
                $where['did'] = $did;
            }elseif (!empty($cid) && empty($did)) {
                $where['cid'] = $cid;
                $where['did'] = $did;
            }
            $curriculum = Curriculum::field('img,course,quantity,support,duration,createtime')
                        ->where($where)
                        ->page($page,$limit)->select();  //课程
        }
        $ucurriculum = UserCurriculum::where('uid',$userId)->select();
        if ($curriculum) {
            foreach ($curriculum as $key => $val) {
                $curriculum[$key]['schedule'] = '0%';
                foreach ($ucurriculum as $k => $v) {
                    if ($v['cu_id'] == $val['id'] ) {
                        $count = UserChapter::where(['uid'=>$userId,'cu_id'=>$val['id'],'satae'=>3])->count();
                        $curriculum[$key]['schedule'] = bcmul(bcdiv($count,$val['quantity'],2),100) .'%';
                    }
                }
                if ($val['img']) {
                    $curriculum[$key]['img'] = 'https://' . $_SERVER['HTTP_HOST'] . $val['img'];
                }
                if ($val['createtime']) {
                    $curriculum[$key]['createtime'] = date('Y-m-d',$val['createtime']);
                }
                $curriculum[$key]['quantity'] = $val['quantity'].'章节';
                $curriculum[$key]['duration'] = '总教学时长：'.$val['duration'];
            }
        }
        $data = [
            'curriculum' => $curriculum,
            'count' => count($curriculum),
            ];
        $this->success('请求成功',$data);

    }



    /**
     * 课程详情
     */
    public function details() {
        $id = $this->request->get('id');
        if (empty($id)) {
            $this->error('传参错误');
        }
        $userId = $this->auth->id;
        $curriculum = Curriculum::where(['id'=>$id])->find();  //课程

        $count = UserChapter::where(['uid'=>$userId,'cu_id'=>$id,'satae'=>3])->count();
        $curriculum['schedule'] = bcmul(bcdiv($count,$curriculum['quantity'],2),100) .'%';
        $chapter = Chapter::where(['cu_id'=>$id])->select();
        $UserChapter = UserChapter::where(['uid'=>$userId,'cu_id'=>$id])->select();
        if ($curriculum['img']) {
                $curriculum['img'] = 'https://' . $_SERVER['HTTP_HOST'] . $curriculum['img'];
            }
        if ($curriculum['createtime']) {
                $curriculum['createtime'] = date('Y-m-d',$curriculum['createtime']);
            }
        foreach ($chapter as $key => $val) {
            if ($val['img']) {
                $chapter[$key]['img'] = 'https://' . $_SERVER['HTTP_HOST'] . $val['img'];
            }
            if ($val['createtime']) {
                $chapter[$key]['createtime'] = date('Y-m-d',$val['createtime']);
            }
            switch ($val['type']) {
                case 1:
                    $chapter[$key]['types'] = '视频';
                    break;
                case 2:
                    $chapter[$key]['types'] = '文本';
                    break;
                case 3:
                    $chapter[$key]['types'] = '图片';
                    break;
            }
            $satae = 1;
            foreach ($UserChapter as $k => $v) {
                if ($v['ch_id'] == $val['id']) {
                    $satae = $v['satae'];
                }
                $chapter[$key]['satae'] = $satae;
            }
        }
        $curriculum['chapter'] = $chapter;
        $this->success('请求成功',$curriculum);

    }


    /**
     * 章节详情
     */
    public function chapter_details() {
        $id = $this->request->get('id');
        $sid = $this->request->get('sid');
        $userId = $this->auth->id;
        if (empty($id)) {
            $this->error('传参错误');
        }
        $UserChapter = UserChapter::where(['uid'=>$userId,'ch_id'=>$sid])->find();
        
        /*if (!$UserChapter || $UserChapter['satae'] != 3) {
            $this->error('上一章节学习还没有结束');
        }*/
        
        $chapter = Chapter::where(['id'=>$id])->find();
        $UserChapter = UserChapter::where(['uid'=>$userId,'ch_id'=>$id])->find();
        if ($UserChapter) {
            $chapter['satae'] = $UserChapter['satae'];
        } else {
            $data = [
                'uid' => $userId,
                'cu_id' => $chapter['cu_id'],
                'ch_id' => $id,
                'satae' => 1,
                'createtime' => time(),
            ];
            UserChapter::insert($data);
        }
        if ($chapter['img']) {
                $chapter['img'] = 'https://' . $_SERVER['HTTP_HOST'] . $chapter['img'];
            }
        if ($chapter['video']) {
                $chapter['video'] = 'https://' . $_SERVER['HTTP_HOST'] . $chapter['video'];
            }            
        if ($chapter['createtime']) {
                $chapter['createtime'] = date('Y-m-d',$chapter['createtime']);
            }
        $this->success('请求成功',$chapter);
    }




    /**
     * 学习结束
     */
    public function finish() {
        $id = $this->request->get('id');
        $satae = $this->request->get('satae');
        $userId = $this->auth->id;
        if (empty($id)) {
            $this->error('传参错误');
        }
        
        $UserChapter = UserChapter::where(['uid'=>$userId,'ch_id'=>$id])->find();
        if ($satae == 3) {
            if ($UserChapter && $UserChapter['satae'] !=3) {
                UserChapter::where(['uid'=>$userId,'ch_id'=>$id])->update(['satae'=>3]);
                $chapter = Chapter::where(['id'=>$id])->find();
                $score = User::where('id',$userId)->value('score');
                //奖励积分，增加记录
                $data = [
                    'user_id' => $userId,
                    'before'=> $score,
                    'score' => $chapter['score'],
                    'after' => bcadd($chapter['score'],$score),
                    'type' => 1,
                    'memo' =>'课程奖励'
                ];
                ScoreLog::create($data);
                User::where('id',$userId)->inc('total_points', $chapter['score'])->update();
                User::where('id',$userId)->inc('score', $chapter['score'])->update();
                $this->success('学习完成，奖励'.$chapter['score'].'积分');
            }
        } else {
            $UserChapter = UserChapter::where(['uid'=>$userId,'ch_id'=>$id])->update(['satae'=>$satae]);
            $this->success('提前退出，无法获得积分');
        }
        
    }



    /**
     * 精选练习
     */
    public function statistics() {
        $type = $this->request->get('type');
        $userId = $this->auth->id;
        $type = empty($type)?1:$type;
        $topic = Topic::where(['type'=>$type])->count();
        $error = ErrorSet::where(['uid'=>$userId,'type'=>$type])->count();
        $practice = PracticeRecord::where(['uid'=>$userId,'type'=>$type])->count();
        $info = User::field('nickname,avatar')->where('id',$userId)->find();
        if ($info['avatar']) {
            $info['avatar'] = 'https://' . $_SERVER['HTTP_HOST'] . $info['avatar'];
        } else {
            $info['avatar'] = 'https://' . $_SERVER['HTTP_HOST'] . '/assets/img/avatar.png';
        }
        $data = [
            'topic' =>$topic,
            'error' =>$error,
            'practice' =>$practice,
            'correct' => $practice - $error,
            'avatar' =>$info['avatar'],
            'nickname' =>$info['nickname'],
            ];
        
        $this->success('获取成功',$data);
        
    }

    

    /**
     * 获取当前分类下没有做过的题目
     */ 
    public function practice() {
        $type = $this->request->get('type');
        $id = $this->request->get('id');
        $userId = $this->auth->id;
        $page = $this->request->get('page');
        $limit = $this->request->get('limit');
        $type = empty($type)?1:$type;
        if (!$id) {
            $id = PracticeRecord::where(['uid'=>$userId,'type'=>$type])->order('id', 'asc')->value('id');
        }
        if ($id) {
            $topic = Topic::where(['id'=>['>',$id],'type'=>$type])->limit(1)->order('id', 'asc')->select();
        } else {
            $topic = Topic::where(['type'=>$type])->limit(1)->order('id', 'asc')->select();
        }
        
        foreach ($topic as $key => $val) {
            if ($val['type'] != 3) {
                $topic[$key]['answer'] = explode(',',$val['answer']);
            }
            if ($val['type'] == 2 || $val['type'] == 5) {
                $topic[$key]['correct_answer'] = explode(',',$val['correct_answer']);
            }
            switch ($val['type']) {
                case 1:
                    $topic[$key]['types'] = '单选题';
                    break;
                case 2:
                    $topic[$key]['types'] = '多选题';
                    break;
                case 4:
                    $topic[$key]['types'] = '判断题';
                    break;
                case 5:
                    $topic[$key]['types'] = '填空题';
                    break;
            }
        }
        $topic_count = Topic::where(['type'=>$type])->count();
        $error = ErrorSet::where(['uid'=>$userId,'type'=>$type])->count();
        $practice = PracticeRecord::where(['uid'=>$userId,'type'=>$type])->count();
        $data = [
            'topic_count' =>$topic_count,
            'error' =>$error,
            'practice' =>$practice,
            'correct' => $practice - $error,
            'topic' =>$topic,
            ];
        $this->success('获取成功',$topic);
    }


    /**
     * 提交答案(一题一次)
     */
    public function submit() {
        $type = $this->request->post('type');
        $id = $this->request->post('id');
        $satae = $this->request->post('satae');
        $answer = $this->request->post('answer');
        $userId = $this->auth->id;
        $type = empty($type)?1:$type;
        if ($satae == 2) {
            ErrorSet::insert(['uid'=>$userId,'to_id'=>$id,'type'=>$type,'answer'=>$answer]);
        } 
        PracticeRecord::insert(['uid'=>$userId,'to_id'=>$id,'type'=>$type,'answer'=>$answer,'satae'=>$satae]);
        
        if (!$id) {
            $id = PracticeRecord::where(['uid'=>$userId,'type'=>$type])->order('id', 'asc')->value('id');
        }
        if ($id) {
            $topic = Topic::where(['id'=>['>',$id],'type'=>$type])->limit(1)->order('id', 'asc')->select();
        } else {
            $topic = Topic::where(['type'=>$type])->limit(1)->order('id', 'asc')->select();
        }
        
        foreach ($topic as $key => $val) {
            if ($val['type'] != 3) {
                $topic[$key]['answer'] = explode(',',$val['answer']);
            }
            if ($val['type'] == 2 || $val['type'] == 5) {
                $topic[$key]['correct_answer'] = explode(',',$val['correct_answer']);
            }
            switch ($val['type']) {
                case 1:
                    $topic[$key]['types'] = '单选题';
                    break;
                case 2:
                    $topic[$key]['types'] = '多选题';
                    break;
                case 4:
                    $topic[$key]['types'] = '判断题';
                    break;
                case 5:
                    $topic[$key]['types'] = '填空题';
                    break;
            }
        }
        $topic_count = Topic::where(['type'=>$type])->count();
        $error = ErrorSet::where(['uid'=>$userId,'type'=>$type])->count();
        $practice = PracticeRecord::where(['uid'=>$userId,'type'=>$type])->count();
        $data = [
            'topic_count' =>$topic_count,
            'error' =>$error,
            'practice' =>$practice,
            'correct' => $practice - $error,
            'topic' =>$topic,
            ];
        $this->success('获取成功',$data);
    }




    /**
     * 练习记录
     */ 
    public function practice_record() {
        $type = $this->request->get('type');
        $userId = $this->auth->id;
        $page = $this->request->get('page');
        $limit = $this->request->get('limit');
        $page = empty($page) ? 1 : $page;
        $limit = empty($limit) ? 10 : $limit;
        $type = empty($type)?1:$type;
        $practice = PracticeRecord::where(['uid'=>$userId,'type'=>$type])->page($page,$limit)->select();
        if (!$practice) {
            $this->success('暂无记录',[]);
        }
        $ids = array_column($practice,'to_id');
        $topic = Topic::where(['id'=>['in',$ids]])->select();
        foreach ($topic as $key => $val) {
            if ($val['type'] != 3) {
                $topic[$key]['answer'] = explode(',',$val['answer']);
            }
            if ($val['type'] == 2 || $val['type'] == 5) {
                $topic[$key]['correct_answer'] = explode(',',$val['correct_answer']);
            }
            switch ($val['type']) {
                case 1:
                    $topic[$key]['types'] = '单选题';
                    break;
                case 2:
                    $topic[$key]['types'] = '多选题';
                    break;
                case 4:
                    $topic[$key]['types'] = '判断题';
                    break;
                case 5:
                    $topic[$key]['types'] = '填空题';
                    break;
            }
            
            foreach ($practice as $k => $v) {
                if ($v['to_id'] == $val['id']) {
                    if ($val['type'] == 3 || $val['type'] == 5) {
                        $topic[$key]['user_answer'] = explode(',',$v['answer']);
                    } else {
                        $topic[$key]['user_answer'] = $v['answer'];
                    }
                    $topic[$key]['satae'] = $v['satae'];
                }
            }
        }
        $data = [
            'list' => $topic,
            'count' => count($topic),
            ];
        $this->success('获取成功',$data);
    }




     /**
     * 错题记录
     */ 
    public function errorSet() {
        $type = $this->request->get('type');
        $userId = $this->auth->id;
        $page = $this->request->get('page');
        $limit = $this->request->get('limit');
        $page = empty($page) ? 1 : $page;
        $limit = empty($limit) ? 10 : $limit;
        $type = empty($type)?1:$type;
        $error = ErrorSet::alias('e')
                ->field('t.*,e.answer as user_answer')
                ->join('topic t','e.to_id=t.id')
                ->where(['uid'=>$userId,'e.type'=>$type])->page($page,$limit)->select();
        foreach ($error as $key => $val) {
            if ($val['type'] != 3) {
                $error[$key]['answer'] = explode(',',$val['answer']);
            }
            if ($val['type'] == 2 || $val['type'] == 5) {
                $error[$key]['correct_answer'] = explode(',',$val['correct_answer']);
            }
            switch ($val['type']) {
                case 1:
                    $error[$key]['types'] = '单选题';
                    break;
                case 2:
                    $error[$key]['types'] = '多选题';
                    break;
                case 4:
                    $error[$key]['types'] = '判断题';
                    break;
                case 5:
                    $error[$key]['types'] = '填空题';
                    break;
            }
        }
        $data = [
            'list' => $error,
            'count' => count($error),
            ];
        $this->success('获取成功',$error);
    }


    

    










}